package cn.leftsite.netty.test.preset;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLEngine;

/**
 * 使用HTTPS
 * @author wangjinqiang
 * @date 2019-05-30
 */
public class HttpCodecInitializer extends ChannelInitializer<Channel> {
    private final SslContext sslContext;
    private final  boolean isClient;

    public HttpCodecInitializer(SslContext sslContext, boolean isClient) {
        this.sslContext = sslContext;
        this.isClient = isClient;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        SSLEngine sslEngine = sslContext.newEngine(ch.alloc());

        // 将 SslHandler 添加到 ChannelPipeline 中以使用 HTTPS
        pipeline.addFirst("ssl", new SslHandler(sslEngine));

        if (isClient){
            // 如果是客户端，添加 HttpClientCodec
            pipeline.addLast("codec", new HttpClientCodec());
        }else {
            // 如果是服务端，添加 HttpServerCodec
            pipeline.addLast("codec", new HttpServerCodec());
        }
    }
}
